package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
)

var filename = "D:\\Sample\\go\\go-learning\\11-file\\test.txt"

func readFile() {
	file, err := os.Open(filename)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("file=%v\n", file)
	//读取文件
	reader := bufio.NewReader(file)
	for {
		str, err := reader.ReadString('\n')
		fmt.Print(str)
		if err == io.EOF {
			break
		}
	}
	file.Close()

	fmt.Println("")
	//一次性读取
	content, err1 := ioutil.ReadFile(filename)
	if err1 != nil {
		fmt.Println(err1)
		return
	}

	fmt.Println(string(content))
}

func writeFile() {
	file, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0666)
	if err != nil {
		return
	}
	defer file.Close()

	str := "hello,yangjie"
	writer := bufio.NewWriter(file)
	writer.WriteString(str)
	writer.Flush()
}

func writeFileWithIoutil() {
	data := []byte("datainfo")
	err := ioutil.WriteFile(filename, data, 0666)
	if err != nil {
		fmt.Println(err)
	}
}

func main() {
	readFile()
	writeFile()
	writeFileWithIoutil()
}
